package belf.migrate.api.source;

import java.security.SecureRandom;
import java.util.Random;

/**
 * A numeric ID or a numeric ID range of this database client, The numeric ID syntax is like
 * '5400', the numeric ID range syntax is like '5400-5408', The numeric ID range syntax is
 * required when 'scan.incremental.snapshot.enabled' enabled. Every ID must be unique across all
 * currently-running database processes in the MySQL cluster. This connector joins the MySQL
 * cluster as another server (with this unique ID) so it can read the binlog. By default, a
 * random number is generated between 6500 and 2,148,492,146, though we recommend setting an
 * explicit value."
 */
public class ServerIdRange {

    public static long serverId() {
        Random random = new Random();
        long min = 6500;
        long max = 2148492146L;

        // 生成范围[min, max]内的随机整数
        return getRandomLongInRange(min, max);
    }

    public static long getRandomLongInRange(long lowerBound, long upperBound) {
        if (lowerBound >= upperBound) {
            throw new IllegalArgumentException("Lower bound must be less than upper bound");
        }

        SecureRandom secureRandom = new SecureRandom();
        long range = upperBound - lowerBound + 1;
        long randomValue = lowerBound + (long)(secureRandom.nextDouble() * range);

        return randomValue;
    }
}
